package com.syqc.videos

import autodispose2.autoDispose
import com.syqc.base.ChooseTimeViewModel
import com.syqc.comlib.UserConstant
import com.syqc.comlib.utils.AppContext
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.HistoryVideo
import com.syqc.entity.KeyValue
import com.syqc.entity.VideoHost
import com.syqc.entity.VideosPass
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import com.syqc.utils.TimeUtil
import com.syqc.utils.ToolsUtil
import com.syqc.utils.UrlUtil
import com.syqc.utils.VideoHostUtil
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.subjects.PublishSubject
import java.net.URLEncoder
import kotlin.concurrent.thread

/**
 *@Author Jasper
 *@Time   2020/9/19
 *@Desc   车辆历史
 */
class CarHistoryVideoViewModel : ChooseTimeViewModel() {
    private val userIdEncode =
        URLEncoder.encode(UserConstant.current_userId.replace(".", "_"), "utf-8")
    private val user = "$userIdEncode*${UserConstant.current_pwd_md5}"

    //是否查询终端视频
    var isTmn = true
    private lateinit var videoHost: VideoHost
    var carId: String = ""
        set(value) {
            field = value
            if (value.isNotEmpty()) videoHost = VideoHostUtil.getVideoHost(value)
        }

    var carName = ""
    var videos = ""
        set(value) {
            handleVideos(value)
        }

    //通道下标
    var tmnPass: Int = 0

    //通道
    var pass: String = "0"

    //音视频资源下标
    var tmnRes: Int = 0

    //码流下标
    var tmnStream: Int = 0

    //存储器下标
    var tmnStorage: Int = 0

    //弹窗类型 0.通道 1.视频 2.码流 3.存储器
    var popupType = 0


    //视频通道
    val videoPassList = ArrayList<KeyValue>()

    val entitySub: PublishSubject<MutableList<HistoryVideo.Result>>
            by lazy { PublishSubject.create() }
    private var allPass = ""
    private var passName = ""

    fun init(allPass: String, passName: String) {
        this.allPass = allPass
        this.passName = passName
        videoPassList.clear()
        videoPassList.add(KeyValue("0", allPass))
    }

    /**
     * 视频通道处理
     */
    private fun handleVideos(videos: String) {
        videoPassList.clear()
        videoPassList.add(KeyValue("0", allPass))
        if (videos.isNotEmpty()) {
            val entity = GsonUtil.formObject<VideosPass>(videos)
            if (entity.vs == null) return
            val passEntitys = entity.vs.split(",")
            for (pass in passEntitys) {
                val passInfos = pass.split(":")
                val passNum = passInfos[0]
                if (passInfos[1].isNotEmpty()) {
                    videoPassList.add(KeyValue(passNum, passInfos[1]))
                } else {
                    videoPassList.add(KeyValue(passNum, "$passName $passNum"))
                }
            }
        }
    }

    /**
     * 获取视频列表
     */
    fun getTmVideosInfo(startTime: String, endTime: String) {
        if (carId.isEmpty()) {
            toast(R.string.hint_toast_choose_car)
            return
        }
        when (videoHost.isClient) {
            null -> {
                thread {
                    val isClient = ToolsUtil.isReachableByTcp(videoHost.ip, videoHost.port)
                    VideoHostUtil.changeHost(videoHost.index, isClient)
                    if (isClient) {
                        getInfos(startTime, endTime)
                    } else {
                        toast(VideoHostUtil.getHost(videoHost) + "\n" + AppContext.getDescById(R.string.toast_port_faile))
                    }
                }
            }

            false -> {
                toast(VideoHostUtil.getHost(videoHost) + "\n" + AppContext.getDescById(R.string.toast_port_faile))
            }

            else -> {
                getInfos(startTime, endTime)
            }
        }

    }

    private fun getInfos(startTime: String, endTime: String) {
        val start = TimeUtil.instance.formatHms(startTime).substring(2)
        val end = TimeUtil.instance.formatEndHms(endTime).substring(2)
        if (isTimeOk(startTime, endTime)) return
        toastLoading(true)
        ServiceHelper.getRepository().getVideoState(getUrl(start, end))
            .autoDispose(this)
            .subscribe(Consumer {
                toastLoading(false)

                val videoEntity =
                    GsonUtil.formObject<HistoryVideo>(it)
                if (videoEntity.state != "0") {
                    toast(UrlUtil.getToastMap()[videoEntity.state] ?: "")
                    return@Consumer
                }
                if (videoEntity.result.isNullOrEmpty()) {
                    toast(R.string.desc_no_about_data)
                    return@Consumer
                }
                videoEntity.result.forEach { item ->
                    item.channelName = getChannel(item.channel)
                }
                entitySub.onNext(videoEntity.result)

            }, error)
    }

    private fun getChannel(channel: Int): String {

        videoPassList.forEach {
            if (it.key == channel.toString()) return it.value
        }
        return ""
    }

    private fun getUrl(startTime: String, endTime: String): String {
        return if (isTmn) {
            "${VideoHostUtil.getHost(videoHost)}/httpflv.hquery.$user.$carId.$pass.$startTime.$endTime.$tmnRes.$tmnStream.$tmnStorage"
        } else {
            "${VideoHostUtil.getHost(videoHost)}/httpflv.squery.$user.$carId.$pass.$startTime.$endTime"
        }
    }

    override fun onCleared() {
        super.onCleared()
        VideoHostUtil.clearHostsClient()
    }

}
